package String;

public class _541_ReverseStringII {
    public String reverseStr0(String s, int k) {
        String str = s;
        String result = "";
        int length = s.length();
        for (int i = 0; i <= length - 1; i++) {

            if (i + 2 * k <= length) {

                for (int j = i + k - 1; j >= i; j--) {
                    result += str.charAt(j);
                }
                for (int j = i + k; j < i + 2 * k; j++) {
                    result += str.charAt(j);
                }
                i = i + 2 * k-1;
            } else if ((i + 2 * k > length) && (i + k <= length)) {
                for (int j = i + k - 1; j >= i; j--) {
                    result+=str.charAt(j);
                }
                for (int j = i+k; j <=length-1; j++) {
                    result+=str.charAt(j);
                }
                break;
            } else {
                for(int j=length-1;j>=i;j--) {
                    result+=str.charAt(j);
                }
                break;
            }
        }
        return result;
    }

    //solution 2,change the original string
    public String reverseStr(String s, int k) {
        int i = 0;
        char[] arr = s.toCharArray();
        while (i <= arr.length - 1) {
            reverseSub(arr, i, i + k - 1);
            i = i + 2 * k;
        }
        return String.valueOf(arr);
    }

    public void reverseSub(char[] arr, int from, int to) {
        int i =from;
        if (to > arr.length - 1) {
            to  = arr.length -1;
        }
        while (i < to) {
            char temp = arr[i];
            arr[i] = arr[to];
            arr[to] = temp;
            i++;
            to--;
        }
    }
}
